<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="社区" prop="communityId">
        <el-select
          v-model="queryParams.communityId"
          placeholder="请选择社区"
          clearable
          filterable
        >
          <el-option v-for="c in community" :label="c.name || c.communityId" :value="c.communityId" />
        </el-select>
      </el-form-item>
      <el-form-item label="车库名称" prop="garageName">
        <el-input
          v-model="queryParams.garageName"
          placeholder="请输入车库名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位区域" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入车位区域"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位号" prop="parkingNo">
        <el-input
          v-model="queryParams.parkingNo"
          placeholder="请输入车位号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌" prop="prefixLetter">
        <el-input
          v-model="queryParams.prefixLetter"
          placeholder="请输入车牌"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位面积" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入车位面积"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车位编号" prop="parkingNumber">
        <el-input
          v-model="queryParams.parkingNumber"
          placeholder="请输入车位编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['comsys:space:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['comsys:space:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['comsys:space:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['comsys:space:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['comsys:space:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spaceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车位ID" align="center" prop="parkingSpaceId" />
      <el-table-column label="社区" align="center" prop="communityId">
        <template #default="scope">
          <span>{{ getCommunityName(scope.row.communityId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车库名称" align="center" prop="garageName" />
      <el-table-column label="车位区域" align="center" prop="areaName" />
      <el-table-column label="车位号" align="center" prop="parkingNo" />
      <el-table-column label="车位类型" align="center" prop="parkingType" />
      <el-table-column label="车牌" align="center" prop="prefixLetter" />
      <el-form-item label="车位面积" prop="area">
        <el-input v-model="queryParams.area" placeholder="请输入车位面积">
          <template #append>㎡</template>
        </el-input>
      </el-form-item>
      <el-table-column label="车位编号" align="center" prop="parkingNumber" />
      <el-table-column label="车位状态" align="center" prop="status"/>
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="车位图片" align="center" prop="images">
        <template #default="scope">
          <div v-if="scope.row.images" class="table-image-container">
            <el-image
                :src="scope.row.images"
                :preview-src-list="[scope.row.images]"
                class="table-preview-item"
                fit="cover"
                lazy
            />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['comsys:space:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['comsys:space:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车位管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="spaceRef" :model="form" :rules="rules" label-width="80px">
        <!-- 社区下拉框 -->
        <el-form-item label="社区">
          <el-select v-model="form.communityId" placeholder="请选择社区" clearable>
            <el-option v-for="c in community" :label="c.communityName || c.name || c.communityId" :value="c.communityId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="车库名称" prop="garageName">
          <el-input v-model="form.garageName" placeholder="请输入车库名称" />
        </el-form-item>
        <el-form-item label="车位区域" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入车位区域" />
        </el-form-item>
        <el-form-item label="车位号" prop="parkingNo">
          <el-input v-model="form.parkingNo" placeholder="请输入车位号" />
        </el-form-item>
        <el-form-item label="车牌" prop="prefixLetter">
          <el-input v-model="form.prefixLetter" placeholder="请输入车牌" />
        </el-form-item>
        <el-form-item label="车位面积" prop="area">
          <el-input v-model="form.area" placeholder="请输入车位面积" />
        </el-form-item>
        <el-form-item label="车位编号" prop="parkingNumber">
          <el-input v-model="form.parkingNumber" placeholder="请输入车位编号" />
        </el-form-item>
        <el-form-item label="车位状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择或输入车位状态" clearable filterable allow-create>
            <el-option label="有效" value="有效"></el-option>
            <el-option label="空置" value="空置"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片(JSON数组)" prop="images">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/upload/img"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="headers"
          >
            <img v-if="form.images" :src="form.images" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Space">
import { listSpace, getSpace, delSpace, addSpace, updateSpace } from "@/api/comsys/space"
import {Plus} from "@element-plus/icons-vue";
import {getToken} from "@/utils/auth.js";
import {ElMessage} from "element-plus";
import request from '@/utils/request'


const { proxy } = getCurrentInstance()

const spaceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const router = useRouter()

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    communityId: null,
    garageName: null,
    areaName: null,
    parkingNo: null,
    parkingType: null,
    prefixLetter: null,
    area: null,
    parkingNumber: null,
    status: null,
    description: null,
    images: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询车位管理列表 */
function getList() {
  loading.value = true
  listSpace(queryParams.value).then(response => {
    spaceList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    parkingSpaceId: null,
    communityId: null,
    garageName: null,
    areaName: null,
    parkingNo: null,
    parkingType: null,
    prefixLetter: null,
    area: null,
    parkingNumber: null,
    status: null,
    description: null,
    images: null,
    createTime: null,
    updateTime: null
  }
  proxy.resetForm("spaceRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.parkingSpaceId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 若查询区已选择社区，则带入新增弹窗
  if (queryParams.value.communityId) {
    form.value.communityId = queryParams.value.communityId
  }
  open.value = true
  title.value = "添加车位管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _parkingSpaceId = row.parkingSpaceId || ids.value
  getSpace(_parkingSpaceId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改车位管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["spaceRef"].validate(valid => {
    if (valid) {
      if (form.value.parkingSpaceId != null) {
        updateSpace(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSpace(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _parkingSpaceIds = row.parkingSpaceId || ids.value
  proxy.$modal.confirm('是否确认删除车位管理编号为"' + _parkingSpaceIds + '"的数据项？').then(function() {
    return delSpace(_parkingSpaceIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('comsys/space/export', {
    ...queryParams.value
  }, `space_${new Date().getTime()}.xlsx`)
}

/** 导入按钮操作 */
function handleImport() {
  router.push({ path: '/comsys/space/import' })
}

const headers = ref({ Authorization: "Bearer " + getToken() })
// 图片上传
const handleAvatarSuccess = (
    response
) => {
  ElMessage.success("上传成功")
  form.value.images = response.msg
  // console.log(response)
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

const community = ref([])
//显示社区id下拉框
const initCommunity = () =>{
  request({
    url: `/communityVo/getCommunityVoNameById`,
    method: 'get'
  }).then((response) => {
    community.value = response.data;
  })
}

// 映射社区名称
const communityMap = ref({})
const getCommunityName = (cid) => {
  if (cid == null) return '-'
  const key = typeof cid === 'string' ? cid : String(cid)
  return communityMap.value[key] || communityMap.value[cid] || cid
}

watch(community, (list) => {
  const map = {}
  ;(list || []).forEach(c => {
    if (c && c.communityId != null) {
      map[c.communityId] = c.name || c.communityName || c.communityId
    }
  })
  communityMap.value = map
})
initCommunity()
getList()
</script>

<style scoped>
.avatar-uploader, .avatar-uploader.el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover { border-color: var(--el-color-primary); }
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  object-fit: cover;
  display: block;
}
</style>
